import React, { Component } from 'react';
import service from '../../api'
import './Cart.scss'
import { connect } from 'react-redux'
import { NavBar, Tag, Ellipsis, Toast, ErrorBlock, Button, Divider, SwipeAction, Dialog, Checkbox, Stepper } from 'antd-mobile'
// import { Action, SwipeActionRef } from 'antd-mobile/es/components/swipe-action'
import Guesslike from '../../components/Guesslike';

interface Cart {
    myRef: any
    refs: any
}
class Cart extends Component<any, any> {
    constructor(props: any) {
        super(props)
        this.myRef = React.createRef()
        this.state = {
            cartlist: [],
            isEmpty: false,
            sum: 0,
        }
    }
    async componentDidMount() {
        if (!localStorage.getItem('token')) {
            this.props.history.replace('/login')
        }
        await this.getCartList()
    }
   
    back() {
        console.log(this.props)
        // console.log(this.props);
        this.props.history.push('/index/home')
    }
    async getCartList() {
        var userid = localStorage.getItem('userid')
        var res = await service.cart.getCartlist({ userid })
        // console.log(res)
        if (res.data.code === '200') {
            this.setState({
                cartlist: res.data.data
            }, () => {
                console.log(this.state.cartlist)
                var newarr = this.state.cartlist.filter((item: any) => item.flag);
                var sum = newarr.reduce((sum: number, item: any) => {
                    return sum += Math.ceil(item.originprice * item.discount / 10) * item.num
                }, 0)
                var type = this.state.cartlist.every((item: any) => item.flag)
                this.setState({
                    sum,
                    type
                })
            })
            return res.data.data
        }
        else {
            this.setState({
                isEmpty: true,
            })
        }
    }
    async deleteOne(e: any, cartid: string) {
        console.log(cartid)
        await Dialog.confirm({
            content: '确定移除该商品？',
            onConfirm: async () => {
                await service.cart.removeOne({ cartid }).then(res => {
                    console.log(res)
                    if (res.data.code === '200') {
                        Toast.show({
                            icon: 'success',
                            content: '删除成功',
                            position: 'center',
                        })
                        this.getCartList()
                    }
                    else {
                        Toast.show({
                            icon: 'fail',
                            content: '删除失败',
                            position: 'center',
                        })
                    }
                })
            },
        })
        // console.log(this.refs[cartid])
        this.refs[cartid].close()
    }
    onChange(cartid: string, num: number) {
        // console.log(cartid, num)
        service.cart.doUpdateCartNum({ cartid, num }).then(res => {
            // console.log(res);
            this.getCartList()
        })
    }
    async selectOne(flag: boolean, cartid: string) {
        var arr = await this.getCartList()
        var type = arr.every((item: any) => item.flag)
        this.setState({
            type
        })
        service.cart.selectOne({ flag, cartid }).then(res => {
            // console.log(res);
            this.getCartList()
        })
    }
    selectAll(type: boolean) {
        console.log(type)
        var arr = this.state.cartlist.map((item: any) => {
            item.flag = type
            return item
        })
        this.setState({
            cartlist: arr,
            type
        })
        var userid = localStorage.getItem('userid')
        service.cart.selectAll({ type, userid }).then(res => {
            if (res.data.code === '200') {
                this.getCartList()
            }
        })
    }
    async deleteAll() {
        var userid = localStorage.getItem('userid')
        await Dialog.confirm({
            content: '确定清空购物车？',
            onConfirm: async () => {
                await service.cart.removeAll({ userid }).then(res => {
                    console.log(res)
                    if (res.data.code === '200') {
                        Toast.show({
                            icon: 'success',
                            content: '删除成功',
                            position: 'center',
                        })
                        this.getCartList()
                    }
                    else {
                        Toast.show({
                            icon: 'fail',
                            content: '删除失败',
                            position: 'center',
                        })
                    }
                })
            },
        })
    }
    toAddress() {
        this.props.history.push('/addresslist')
    }
    onOrder() {
        service.order.addOrder({ userid: localStorage.getItem('userid') }).then(res => {
            console.log(res)
            if (res.data.code === '200') {
                Toast.show({
                    content: '添加订单成功'
                })
                setTimeout(()=>{
                    this.props.history.push('/order/'+res.data.time)
                },1000)
            }
        })
    }
    render() {
        // console.log(this.props.address)
        return (
            <div className='cart'>
                <header>
                    <NavBar onBack={() => { this.back() }}>购物车</NavBar>
                </header>
                <main>
                    {
                        this.state.isEmpty ? <> <ErrorBlock
                            image='https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg'
                            style={{
                                '--image-height': '150px',
                            }}
                            description='购物车为空'
                        >
                        </ErrorBlock>
                            <Divider style={{
                                color: '#1677ff',
                                borderColor: '#1677ff',
                                borderStyle: 'dashed',
                            }}>猜你喜欢</Divider>
                            <Guesslike />
                        </> : <>
                            {
                                this.state.cartlist.map((item: any) => {
                                    return (
                                        <SwipeAction
                                            key={item.cartid}
                                            ref={item.cartid}
                                            closeOnAction={false}
                                            closeOnTouchOutside={true}
                                            rightActions={[
                                                {
                                                    key: 'delete',
                                                    text: '删除',
                                                    color: 'danger',
                                                    onClick: async (e) => { await this.deleteOne(e, item.cartid); }
                                                },
                                            ]}
                                        >
                                            <div className='pro'>
                                                <Checkbox checked={item.flag} onChange={(val) => { this.selectOne(val, item.cartid) }} />
                                                <img src={item.img1} alt="" />
                                                <div className='pror' >
                                                    <Ellipsis direction='end' rows={2} content={item.proname} />
                                                    <div className='prices'>
                                                        <span>￥<strong>{Math.ceil(item.originprice * item.discount / 10)}</strong></span>
                                                        <Stepper defaultValue={item.num} min={1} onChange={(value) => { this.onChange(item.cartid, value) }} />
                                                    </div>
                                                </div>
                                            </div>
                                        </SwipeAction>
                                    )
                                })

                            }
                            <Divider style={{
                                color: '#1677ff',
                                borderColor: '#1677ff',
                                borderStyle: 'dashed',
                            }}>猜你喜欢</Divider>
                            <Guesslike />

                            <footer>
                                <Tag color='warning' onClick={() => { this.toAddress() }}>选择地址: {this.props.address.name ?
                                    this.props.address.province + this.props.address.city + this.props.address.county + this.props.address.addressDetail : ''
                                } </Tag>
                                <div className='footer'>
                                    <Checkbox checked={this.state.type} onChange={(val) => { this.selectAll(val) }}>全选</Checkbox>
                                    <Button shape='rounded' size='small' color='danger' onClick={this.deleteAll.bind(this)}>清空购物车</Button>
                                    <span>
                                        总价：<strong>￥{this.state.sum}</strong>
                                    </span>
                                    <Button disabled={this.props.address.name && this.state.sum !== 0 ? false : true}
                                        shape='rounded'
                                        size='small'
                                        onClick={this.onOrder.bind(this)}
                                        style={{ background: 'red', color: '#fff' }}
                                    >立即购买</Button>
                                </div>
                            </footer>
                        </>
                    }
                </main>
            </div>
        );
    }
}
connect(
    (state: any) => {
        return {
            address: state.address
        }
    },
    (dispatch) => {

    }
)
export default connect(
    (state: any) => {
        return {
            address: state.address
        }
    },
)(Cart);